
/**
 * @Describe: 库存模块公用js方法
 * @Date: 2025.6.19
 * @Author:pebble
 * 
 */

/**
 * 图片查看
 * @param barcode
 * @returns
 */
function viewImgP(barcode){
	viewImg(barcode);
}


/**
 * 单据对象集合转json字符串
 */
function saveBeforeLoad(){
	var products = [];
	var status = $("#barcode").val();
	var type = $("#barcode").val();
	var sumQuantity = $("#sumQuantity").val();
	$("#totalQuantity").val(sumQuantity);
		  
	var rows = $('#dataGrid').datagrid('getRows');
	rows.forEach(function(row){
		// 获取每行中指定列的值		    
		products.push({pbId: row.pbId,barcode: row.barcode, nums: row.quantity,scanNums: row.scanNums,comment: row.comment})
	 });	  
	$("#jsons").val(JSON.stringify(products));
}



/**
 * 根据条码或者货号 -新增一条
 * @returns
 */
function insert(){
	var barcode = $("#barcode").val();
	var rows = $('#dataGrid').datagrid('getRows');
	if(barcode == null || barcode == ""){
		 $.messager.alert('提示', '条码为空，请输入条码', 'warning');
	}else{
			 //条码查找
			 if(barcode.length ==12 && isNumber(barcode) ){
				 $.messager.show({
		             title:'扫描提示',
		             msg:'扫描成功，新增条码：'+barcode,
		             timeout:100,
		             showType:'show',
		             style:{
		                 right:'',
		                 top:document.body.scrollTop+document.documentElement.scrollTop,
		                 bottom:''
		             }
		         });
					var storeId = $("#storeId").val();
				    var params= "formBean.pb.barcode=" + barcode + "&formBean.storeId="+storeId ; 
				    $.post("action/headqInventoryFlowJSONAction!scanByBarcodeInvenFlowOrder",params, insertBkProcess,"json");
			 }else{
				 //货号查找
				 searchpbs();
			 }
		}
}

/**
 * insert() - 回调方法
 * @param dataReturn
 * @returns
 */
function insertBkProcess(dataReturn){		
	var isHave= false;
	var barcode = dataReturn.returnValue.pb.barcode;
	var rows = $('#dataGrid').datagrid('getRows');
	
	var product = dataReturn.returnValue.pb.product;
	var numPerHand = product.numPerHand;
	var quantity = 1;
	if ($("#fullOrSingle").val()==1)
	  var quantity = numPerHand;
	
	for(let i=0;i<rows.length;i++){
		 let row = rows[i];
		 if (row.barcode === barcode) { // 自定义条件
		 		var beforeQuantity = row.quantity;
		        var quantity2 = parseInt(row.quantity) + quantity;
		        var newScanNums = row.scanNums+1;			        			        
		        var totalWholePrice = (quantity2 * row.salesPrice).toFixed(1); 
		        var comment = row.comment;
		    	$('#dataGrid').datagrid('updateRow', {
		    	    index: i,
		    	    row: {quantity: quantity2,totalWholePrice: totalWholePrice,scanNums: newScanNums,comment: comment}
		    	});
		    	 $('#barcode').searchbox('setValue', '');
		    		//计算合计
		    	 countSumQuantity();
		    	 $.messager.show({
		             title:'扫描提示',
		             msg:"第【"+row.scanNums+'】次扫描<br>条码:'+ barcode + "<br>行数：" + row.id,
		             timeout:1000,
		             showType:'show',
		             style:{
		                 right:'',
		                 top:document.body.scrollTop+document.documentElement.scrollTop,
		                 bottom:''
		             }
		         });	
		    	 isHave = true;
		    	 break;
		    }
	}
	
	if (isHave == false){
	var chatBox = document.getElementById('chat-box');
	var rows = $('#dataGrid').datagrid('getRows');
	
	var returnCode = dataReturn.returnCode;
	var data = dataReturn.returnValue;
	
	var pbId = dataReturn.returnValue.pb.id;
	
	var productCode = dataReturn.returnValue.pb.product.productCode;
	var brand = dataReturn.returnValue.pb.product.brand.brand_Name;
	var categoryLevel = dataReturn.returnValue.pb.product.categoryLevel1.category_Name;  // 货品类别
	var category = dataReturn.returnValue.pb.product.category.category_Name;  // 货品类别
	var unit = dataReturn.returnValue.pb.product.unit;

	var year = dataReturn.returnValue.pb.product.year.year;
	var quarter = dataReturn.returnValue.pb.product.quarter.quarter_Name;
	var inventoryQ = dataReturn.returnValue.inventoryLevel;
	var color = dataReturn.returnValue.pb.color;
	var colorName = "";
	if (color != null)
		colorName = color.name;
	var wholePrice = dataReturn.returnValue.wholePrice.toFixed(1);
	var totalWholePrice = (quantity * wholePrice).toFixed(1);
	var action1 = 0 ;
	
	var orderType = $("#orderType").val();
	console.log(orderType + "," + inventoryQ);
	if (orderType = 1)
		action1 = quantity + inventoryQ;
	else if (orderType = 2)
		action1 = inventoryQ - quantity;
	else if (orderType = 3)
		action1 = quantity - inventoryQ;
	
	// 添加新行并指定插入位置（如末尾）
	$('#dataGrid').edatagrid('addRow', {
	    index: $('#dataGrid').datagrid('getRows').length, // 插入到最后一行
	    row: { id: rows.length+1,orderType:orderType,pbId: pbId,barcode: barcode,productCode: productCode,colorName: colorName,brand: brand,categoryLevel: categoryLevel,category: category, year: year, quarter: quarter, unit: unit,salesPrice: wholePrice,quantity: quantity,totalWholePrice: totalWholePrice, inventoryQ: inventoryQ,action1: action1,scanNums:1} // 初始数据（可选）
	});
	

	// 获取 searchbox 并设置值
	 $('#barcode').searchbox('setValue', '');
	//计算合计
	 countSumQuantity();

	 chatBox.scrollTop = chatBox.scrollHeight;  
	}
}


/**
 * 删除选中行（带确认提示）
 * @returns
 */
function deleteRow() {
const row = $('#dataGrid').edatagrid('getSelected');
if (!row) {
  $.messager.alert('提示', '请先选择要删除的行', 'warning');
  return;
}

$.messager.confirm('确认', '确定删除该行吗？', function(r) {
  if (r) {
     $('#dataGrid').edatagrid('destroyRow');
     countSumQuantity();
  }
});

}

 

/**
 * 修改选中行（带确认提示）
 * @returns
 */
function updateRow() {
//var editIndex = $('#dataGrid').edatagrid('getEditIndex');  easy ui js存在版本冲突无法使用
var row = $('#dataGrid').edatagrid('getSelected');
var correctNums = $("#correctNums").val();
if(correctNums.length ==0){
	  $.messager.alert('提示', '纠正数量信息为空', 'warning');
	    return;
}else if(!isNumber(correctNums)){
	  $.messager.alert('提示', '纠正数量为非法字符,请重新输入！', 'warning');
	    return;
}

if (!row) {
  $.messager.alert('提示', '请先选择要修改的行！', 'warning');
  return;
}

    var rows = $('#dataGrid').datagrid('getRows');
  	
  	for(let i=0;i<rows.length;i++){
  		let goRow = rows[i]; //行信息
  		if (row.barcode === goRow.barcode) { 
  			let totalWholePrice = (correctNums * goRow.salesPrice).toFixed(1);    			
  			$('#dataGrid').datagrid('updateRow', {
		    	    index: i,
		    	    row: {quantity: correctNums,totalWholePrice: totalWholePrice}
		    	});
  		}
  	}
  	
  	 $.messager.show({
           title:'纠正提示',
           msg:'条码:'+ row.barcode + "纠正数量修改为：" +correctNums ,
           timeout:1000,
           showType:'show',
           style:{
               right:'',
               top:document.body.scrollTop+document.documentElement.scrollTop,
               bottom:''
           }
       });	
  	 $("#correctNums").textbox("setValue","");
  	//计算合计
	 countSumQuantity();
}

/**
 * 计算合计数量
 * @returns
 */
function countSumQuantity(){
	var rows = $('#dataGrid').datagrid('getRows');
	var sumQuantity = 0;
	var inventoryQuantity = 0;
	var correctQuantity = 0;
	for(let i=0;i<rows.length;i++){
		sumQuantity += parseInt(rows[i].quantity);
		inventoryQuantity += parseInt(rows[i].inventoryQ);		
	}
	$("#sumQuantity").val(sumQuantity);
	$("#inventoryQuantity").val(inventoryQuantity);
	
	if ($("#orderType").val() == 1)
		$("#correctQuantity").val(sumQuantity+inventoryQuantity);
	else if ($("#orderType").val() == 2)
		$("#correctQuantity").val(inventoryQuantity - sumQuantity);
	else 
	    $("#correctQuantity").val(sumQuantity-inventoryQuantity);
}


/**
 * 报溢/报损/库存/调货 单据详情-查询条码是否存在
 * @DESCRIBE: DisplayHeadqInvenflowOrder.jsp 
 * @DESCRIBE: DisplayHeadInventoryOrderReport.jsp
 * @DESCRIBE: DisplayHeadInventoryTransferOrder.jsp
 * @returns
 */
function searchBarcode(){
	var barcode = $("#barcode").val();
	if(barcode == null || barcode == ""){
		 $.messager.alert('提示', '条码为空,请输入条码', 'warning');
	}else{
		var rows = $('#dataGrid').datagrid('getRows');
		var isExisit = false;
		var rowInfo = 0;
		for(let i=0;i<rows.length;i++){
			let row = rows[i];
			 if (row.barcode === barcode) {
				 isExisit = true;
				 rowInfo = i+1;
			 }
		}
		if(isExisit){
			 $.messager.alert('提示', '条码:'+barcode+ "在第【"+rowInfo+"】行", 'info');
		}else{
			$.messager.alert('提示', '条码：'+barcode+ "不存在", 'info');
		}	
	}	
}